package com.qdlc.p2p.dal.dao.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.constant.BorrowStatus;
import com.qdlc.p2p.common.constant.BorrowType;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.dao.InviteDao;
import com.qdlc.p2p.dal.model.UserInviteTenderTotal;

/**
 * 好友邀请
 *
 * @author wuaj
 * @version 1.1.0.0
 * @date 2016年03月11日
 */
@Repository("inviteDao")
public class InviteDaoImpl extends BaseDaoImpl<UserInviteTenderTotal> implements InviteDao {

    @Override
    public List<UserInviteTenderTotal> friendYesterdayTenderStatistics() {
        List<UserInviteTenderTotal> logList = new ArrayList<UserInviteTenderTotal>();
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        sql.append("t1.user_id as user_id, "); // 投标用户ID
        sql.append("sum(t1.account) as tender_total, "); // 投标总金额
        sql.append("t3.invite_user "); // 邀请用户ID
        sql.append(" FROM ");
        sql.append(" " + Global.DB_PREFIX + "borrow_tender t1 ");
        sql.append(" INNER JOIN " + Global.DB_PREFIX + "borrow t2 ON t1.borrow_id = t2.id ");
        sql.append(" RIGHT JOIN " + Global.DB_PREFIX + "user_invite t3 ON t1.user_id = t3.user_id ");
        sql.append(" WHERE ");
        sql.append(" TO_DAYS(NOW()) - TO_DAYS(t1.add_time) = 1 "); // 昨日
        sql.append(" AND t2.type <> ").append(BorrowType.TYPE_SECOND); // 秒标不统计
        sql.append(" AND t2.type <> ").append(BorrowType.EXPERIENCE); // 体验标不统计
        sql.append(" AND t2.status in(");
        sql.append(BorrowStatus.STATUS_RECHECK_PASS).append(",");
        sql.append(BorrowStatus.STATUS_REPAYMENT_START).append(",");
        sql.append(BorrowStatus.STATUS_REPAYMENT_DOING).append(",");
        sql.append(BorrowStatus.STATUS_REPAYMENT_DONE);
        sql.append(")");
        sql.append(" GROUP BY t1.user_id");
        Query query = em.createNativeQuery(sql.toString());
        List list = query.getResultList();
        if (list != null && list.size() > 0) {
            Iterator iterator = list.iterator();
            UserInviteTenderTotal userInviteTenderTotal;
            while (iterator.hasNext()) {
                userInviteTenderTotal = new UserInviteTenderTotal();
                Object[] row = (Object[]) iterator.next();
                userInviteTenderTotal.setUserId(Long.parseLong(row[0].toString()));
                userInviteTenderTotal.setTenderTotal(Double.parseDouble(row[1].toString()));
                userInviteTenderTotal.setInviteUser(Long.parseLong(row[2].toString()));
                logList.add(userInviteTenderTotal);
            }
        }
        return logList;
    }
}
